package com.czl.module_service.viewmodel.assetUse

import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.TimeUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.UsageBean
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.czl.module_service.viewmodel.ApprovalFlowViewModel
import java.util.*

class MyUsageApplyDetailViewModel(application: MyApplication, model: DataRepository) :
    ApprovalFlowViewModel(application, model) {

    var tabIndex : Int = 1
    val uc = UiChangeEvent()
    var bean = ObservableField(UsageBean())
    var note = ObservableField("")
    var applicationUseId : Int? = null
    private var cancelTag : Boolean = false
    var taskUserId : String? = null
    class UiChangeEvent {
        val loadCompleteEvent: SingleLiveEvent<UsageBean> = SingleLiveEvent()
        val isCancelCompleteEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
        val backCompleteEvent: SingleLiveEvent<Any> = SingleLiveEvent()
    }

    val onBackClickCommand : BindingCommand<Any> = BindingCommand(BindingAction {
        // 撤销审批
        if (cancelTag) {
            wxApprpveApplication(applicationUseId = applicationUseId, status = 3)
        } else {
            showNormalToast("审批已开始，无法撤回")
        }
    })

    val onAgreeClickCommand : BindingCommand<Any> = BindingCommand(BindingAction {
        // 同意
        nextTaskProcess(taskUserId = taskUserId)
    })

    val onRejectClickCommand : BindingCommand<Any> = BindingCommand(BindingAction {
        // 驳回
        hangUpTaskProcess(taskUserId = taskUserId)
    })

    fun setData(data: UsageBean?) {
        data?.let {
            if (data.applicationType == 0 ) data.applicationTitle = data.userName + "提交的领用申请" else data.applicationTitle = data.userName + "提交的借用申请"
            if (data.applicationType == 1 && data.planSendbakckTime != null) {
                data.planSendbakckTimeStr = TimeUtils.date2String(Date(data.planSendbakckTime !!), "yyyy-MM-dd")
            }
            bean.set(data)
        }
    }

    fun WXGetApplicationInfo(
        applicationUseId: Int? = null
    ) {
        model.mTengYunHttpDataSource.WXGetApplicationInfo(
            GsonUtils.toJson(
                mapOf(
                    "applicationUseId" to applicationUseId
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<UsageBean>>() {
                override fun onResult(t: BaseBean<UsageBean>) {
                    if (t.errorCode == 0) {
                        uc.loadCompleteEvent.postValue(t.data)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    fun isCanCancel(
        applicationUseId: Int? = null,
        businessId : Int? = null
    ) {
        model.mTengYunHttpDataSource.isCanCancel(
            GsonUtils.toJson(
                mapOf(
                    "businessId" to businessId,
                    "relationId" to applicationUseId
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        cancelTag = t.data == true
                        uc.isCancelCompleteEvent.postValue(cancelTag)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }
    private fun wxApprpveApplication(
        applicationUseId: Int? = null,
        status: Int? = null
    ) {
        model.mTengYunHttpDataSource.wxApprpveApplication(
            GsonUtils.toJson(
                mapOf(
                    "applicationUseId" to applicationUseId,
                    "userId" to model.getLocalUserInfo()?.userId,
                    "companyId" to model.getLoginCompanyId()?.toInt(),
                    "status" to status
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        if (status == 1) {
                            showNormalToast("审批通过")
                        }
                        if (status == 2) {
                            showNormalToast("驳回成功")
                        }
                        if (status == 3) {
                            showNormalToast("撤回成功")
                        }
                        LiveBusCenter.postAssetResultReturnEvent(1)
                        uc.backCompleteEvent.postValue(1)
//                        WXGetApplicationInfo(applicationUseId = applicationUseId)
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    private fun nextTaskProcess(
        taskUserId: String? = null
    ) {
        model.mTengYunHttpDataSource.nextTaskProcess(
            GsonUtils.toJson(
                mapOf(
                    "taskUserId" to taskUserId,
                    "taskDesc" to note.get()
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.errorCode == 0) {
                        if (t.data == true) {
                            wxApprpveApplication(applicationUseId = applicationUseId, status = 1)
                        } else {
                            showNormalToast("审批通过")
                            LiveBusCenter.postAssetResultReturnEvent(1)
                            uc.backCompleteEvent.postValue(1)
//                            WXGetApplicationInfo(applicationUseId = applicationUseId)
                        }
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }
    private fun hangUpTaskProcess (
        taskUserId: String? = null
    ) {
        model.mTengYunHttpDataSource.hangUpTaskProcess(
            GsonUtils.toJson(
                mapOf(
                    "taskUserId" to taskUserId,
                    "taskDesc" to note.get()
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.errorCode == 0) {
                        wxApprpveApplication(applicationUseId = applicationUseId, status = 2)
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }
}